package com.gewu.pm.ui.activity.terminal;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.viewpager.widget.ViewPager;

import com.androidkun.xtablayout.XTabLayout;
import com.gewu.pm.R;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.app.AppFragment;
import com.gewu.pm.other.IntentKey;
import com.google.android.material.appbar.AppBarLayout;
import com.hjq.bar.TitleBar;
import com.gewu.pm.ui.fragment.terminal.OrderFragment;
import com.gewu.pm.ui.fragment.terminal.DetailFragment;
import com.gewu.pm.ui.fragment.terminal.ContactFragment;
import com.gewu.pm.ui.fragment.terminal.PromotionFragment;
import com.gewu.pm.ui.fragment.terminal.VisitRecordFragment;
import com.hjq.base.FragmentPagerAdapter;

/**
 * 终端详情页面
 * 
 * 功能：
 * 1. 展示终端基本信息
 * 2. Tab 切换：订单 / 详情 / 联系人 / 促销活动 / 拜访记录
 * 3. 详情页根据是否有营业执照显示不同内容
 */
public final class TerminalDetailActivity extends AppActivity {

    // TitleBar
    private TitleBar mTitleBar;
    private AppBarLayout mAppBarLayout;

    // 终端信息卡片
    private ImageView mTerminalPhotoView;
    private TextView mTerminalNameView;
    private TextView mTerminalCodeView;
    private TextView mTerminalAddressView;
    private TextView mFreezeButton;

    // Tab + ViewPager
    private XTabLayout mTabLayout;
    private ViewPager mViewPager;
    private FragmentPagerAdapter<AppFragment<?>> mPagerAdapter;

    // 传递的数据
    private String mTerminalName;
    private String mTerminalId;  // "1"表示有营业执照，"2"表示无营业执照

    public static void start(Context context, String terminalName, String terminalId) {
        Intent intent = new Intent(context, TerminalDetailActivity.class);
        intent.putExtra(IntentKey.NAME, terminalName);
        intent.putExtra(IntentKey.ID, terminalId);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.terminal_detail_activity;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        // TitleBar
        mTitleBar = findViewById(R.id.tb_title);
        mAppBarLayout = findViewById(R.id.app_bar);

        // 终端信息卡片
        mTerminalPhotoView = findViewById(R.id.iv_terminal_photo);
        mTerminalNameView = findViewById(R.id.tv_terminal_name);
        mTerminalCodeView = findViewById(R.id.tv_terminal_code);
        mTerminalAddressView = findViewById(R.id.tv_terminal_address);
        mFreezeButton = findViewById(R.id.tv_freeze);

        // Tab + ViewPager
        mTabLayout = findViewById(R.id.tab_layout);
        mViewPager = findViewById(R.id.view_pager);

        // 获取传递的数据
        mTerminalName = getString(IntentKey.NAME);
        mTerminalId = getString(IntentKey.ID);
        
        // 判断是否有营业执照
        boolean hasLicense = "1".equals(mTerminalId);

        // 初始化 FragmentPagerAdapter
        mPagerAdapter = new FragmentPagerAdapter<>(this);
        mPagerAdapter.addFragment(OrderFragment.newInstance(), "订单");
        mPagerAdapter.addFragment(DetailFragment.newInstance(hasLicense), "详情");
        mPagerAdapter.addFragment(ContactFragment.newInstance(), "联系人");
        mPagerAdapter.addFragment(PromotionFragment.newInstance(), "促销活动");
        mPagerAdapter.addFragment(VisitRecordFragment.newInstance(), "拜访记录");
        mViewPager.setAdapter(mPagerAdapter);

        // 关联 XTabLayout 和 ViewPager
        mTabLayout.setupWithViewPager(mViewPager);

        // 监听 AppBarLayout 滑动，动态切换 TitleBar 内容
        setupAppBarListener();

        setOnClickListener(mTerminalNameView, mFreezeButton, mTerminalAddressView);
    }

    /**
     * 设置 AppBarLayout 滑动监听
     */
    private void setupAppBarListener() {
        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                int totalScrollRange = appBarLayout.getTotalScrollRange();
                if (totalScrollRange == 0) return;

                // 计算滑动百分比
                float percentage = Math.abs(verticalOffset) / (float) totalScrollRange;

                if (percentage >= 0.8f) {
                    // 滑动到80%时，显示终端名称和缩略图
                    if (!mTerminalName.equals(mTitleBar.getTitle())) {
                        mTitleBar.setTitle(mTerminalName);
                        // TitleBar 右侧显示终端缩略图
                        mTitleBar.setRightIcon(R.drawable.icon_contact);
                        // TitleBar 背景渐变为白色
                        mTitleBar.setBackgroundColor(getResources().getColor(android.R.color.white));
                        // 显示 TitleBar 分割线
                        mTitleBar.setLineVisible(true);
                    }
                } else {
                    // 恢复默认
                    if (!"终端详情".equals(mTitleBar.getTitle())) {
                        mTitleBar.setTitle("终端详情");
                        // 隐藏右侧图标（使用空 Drawable）
                        mTitleBar.setRightIcon((android.graphics.drawable.Drawable) null);
                        // TitleBar 背景渐变为透明
                        mTitleBar.setBackgroundColor(getResources().getColor(android.R.color.transparent));
                        // 隐藏 TitleBar 分割线
                        mTitleBar.setLineVisible(false);
                    }
                }
            }
        });
    }

    @Override
    protected void initData() {
        // 显示终端信息
        mTerminalNameView.setText(mTerminalName);
        // TODO: 加载完整详情数据
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        int id = view.getId();
        if (id == R.id.tv_terminal_name) {
            // 编辑终端名称
            toast("编辑终端名称");
            // TODO: 打开编辑页面
        } else if (id == R.id.tv_freeze) {
            // 冻结
            toast("冻结终端");
            // TODO: 实现冻结功能
        } else if (id == R.id.tv_terminal_address) {
            // 导航
            toast("导航");
            // TODO: 打开导航
        }
    }
}

